//后台配置/数据配置

import React, { Component } from 'react';
import { connect } from 'dva';
import {  Card, Cascader, Button,  Input,Icon,Divider,Table, InputNumber, Popconfirm, Form ,Pagination,Checkbox,DatePicker   } from 'antd';
import style from './DataMapping.less';
//引入字体图标组件
import MyIcon from "../../components/common/MyIcon";
import {bgConQuery} from '../../services/redmoe';
import request from '../../utils/request';
import PublicService from '../../services/PublicService';
import {bgConEdit,bgConQueryTime,bgConQueryEditTime} from '../../services/redmoe';
import moment from 'moment'
const FormItem = Form.Item;
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);
class EditableCell extends React.Component {
    getInput = () => {
      if (this.props.inputType === 'number') {
        return <InputNumber />;
      }
      return <Input />;
    };
  
    render() {
      const {
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        ...restProps
      } = this.props;
      return (
        <EditableContext.Consumer>
          {(form) => {
            const { getFieldDecorator } = form;
            return (
              <td {...restProps}>
                {editing ? (
                  <FormItem style={{ margin: 0 }}>
                    {getFieldDecorator(dataIndex, {
                      rules: [{
                        required: true,
                        message: `Please Input ${title}!`,
                      }],
                      initialValue: record[dataIndex],
                    })(this.getInput())}
                  </FormItem>
                ) : restProps.children}
              </td>
            );
          }}
        </EditableContext.Consumer>
      );
    }
  }


class DataMapping extends Component {
    state={
      data:[],
      editingKey: '' ,
      disabled:true,
      textTime:"",
      defaultValue:null,
      textId:""
    }
    //进入页面事件
    componentDidMount() {

      let Edit = document.getElementById("Edit")
      Edit.style.display="inline"
      let confirm = document.getElementById("confirm")
      confirm.style.display="none"
      let cancel = document.getElementById("cancel")
      cancel.style.display="none"
      //获取表的数据
        bgConQuery().then(data => {
            console.log(data)
            if(data.data.rc == 0) {
              console.log(this.state)
              this.setState({
                data:data.data.ret
              })
            }
        })
        console.log(this.state.data)
        //获取项目开工时间
        bgConQueryTime().then(data => {
          console.log(data)
          this.setState({
            defaultValue:moment(data.data.ret.startTime),
            textId:data.data.ret.id
          })
        })

    }


    constructor(props) {
        super(props);
      
      
        this.columns = [
          {
            title: '序号',
            dataIndex: 'num',
            align:'center',
            width:"10%",
           
          },
          {
            title: '污染物种类',
            dataIndex: 'typeName',
            align:'center',
            editable: true,
            width:"17%"
          },
          {
            title: '单位',
            dataIndex: 'unit',
            align:'center',
            editable: true,
            width:"17%"
          },{
            title: '小时均值',
            dataIndex: 'hourValue',
            align:'center',
            width:"10%",
            editable: true,
            width:"17%"
          },{
            title: '日均值',
            dataIndex: 'dayValue',
            align:'center',
            width:"10%",
            editable: true,
            width:"17%"
          },
          {
            title: '操作',
            align:'center',
            dataIndex: 'operation',
            render: (text, record) => {
              const editable = this.isEditing(record);
              return (
                <div>
                  {editable ? (
                    <span>
                      <EditableContext.Consumer>
                        {form => (
                          <a
                            href="javascript:;"
                            onClick={() => this.save(form, record.key,record)}
                            style={{ marginRight: 8 }}
                          >
                            确定
                          </a>
                        )}
                      </EditableContext.Consumer>
                     
                        <a onClick={() => this.save1()}>取消</a>
                     
                    </span>
                  ) : (
                    <a onClick={() => this.edit(record.key)}> <MyIcon
                    type="icon-gongneng"
                    className={style.MyIcon_gongneng}
                /></a>
                  )}
                </div>
              );
            },
          },
        ];
      }
      //取消事件
        cancel = () => {
            this.setState({ editingKey: '' });
        };
    

        isEditing = (record) => {
            return record.key === this.state.editingKey;
        };
        //编辑事件
        edit(key) {
            this.setState({ editingKey: key });
        }

        //取消事件

        save1(){
          this.setState({  editingKey: '' });
        }

        //确定事件
        save(form, key,record) {
            form.validateFields((error, row) => {

                this.setState({  editingKey: '' });
              if (error) {
                return;
              }
              console.log(record,row)
              
            //编辑事件发出请求
            let data = {
              dayValue:Number(row.dayValue),
              hourValue:Number(row.hourValue),
              typeName:row.typeName,
              unit:row.unit,
              id:record.id
            }
            console.log(data)
            bgConEdit([{...data}]).then(data => {
              console.log(data)
            })




              const newData = [...this.state.data];
              const index = newData.findIndex(item => key === item.key);
              if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                  ...item,
                  ...row,
                });
                this.setState({ data: newData, editingKey: '' });
              } else {
                newData.push(row);
                this.setState({ data: newData, editingKey: '' });
              }
            });
          }
        
        
          //按钮编辑事件
          timeEdit = () => {
            let Edit = document.getElementById("Edit")
            Edit.style.display="none"
            let confirm = document.getElementById("confirm")
            confirm.style.display="inline"
            let cancel = document.getElementById("cancel")
            cancel.style.display="inline"
            this.setState({
              disabled:false
            })
          }
          //取消
          cancel = () => {
            let Edit = document.getElementById("Edit")
            Edit.style.display="inline"
            let confirm = document.getElementById("confirm")
            confirm.style.display="none"
            let cancel = document.getElementById("cancel")
            cancel.style.display="none"
            this.setState({
              disabled:true
            })
          }
          //确定
          confirm = () => {
            let Edit = document.getElementById("Edit")
            Edit.style.display="inline"
            let confirm = document.getElementById("confirm")
            confirm.style.display="none"
            let cancel = document.getElementById("cancel") 
            cancel.style.display="none"
            this.setState({
              disabled:true
            })
            console.log(this.state.defaultValue)
            let data = {
              id:this.state.textId,
              startTime:`${moment(this.state.defaultValue).format("YYYY-MM-DD")} 00:00:00`
            }
            //项目开工时间事件请求
            bgConQueryEditTime({...data})


          }

          textChange = (date,datestring) => {
           this.setState({
            defaultValue:date
           })
          
          }
    

    render() {
      
        const components = {
            body: {
              row: EditableFormRow,
              cell: EditableCell,
            },
          };




        const columns = this.columns.map((col) => {
            if (!col.editable) {
              return col;
            }
            return {
              ...col,
              onCell: record => ({
                record,
                inputType: col.dataIndex === 'age' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: this.isEditing(record),
              }),
            };
          });


        return (
        
            <div>
                        <Card
                            className={style.CardTop}
                        >
                            <div className={style.Top}>
                           
                                项目开工时间:

                                <DatePicker value={this.state.defaultValue} size="small"  onChange={this.textChange}  style={{display:"inline-block",width:150,marginRight:10,marginLeft:5}} disabled={this.state.disabled}/>
                                <Button className="ant-dropdown-link" type="primary" size="small" onClick={this.timeEdit} id="Edit">
                                编辑
                                </Button>
                                <Button  className="ant-dropdown-link" type="primary" size="small" onClick={this.cancel} style={{marginRight:10}} id="cancel">
                                取消
                                </Button>
                                <Button className="ant-dropdown-link" type="primary" size="small" onClick={this.confirm} id="confirm">
                                确定
                                </Button>
                            </div>

                        </Card>
                        <Card
                            className={style.CardBottom}

                        >
                         <div className={style.myTable}>
                         <Table
                          components={components}
                          bordered
                          dataSource={PublicService.transformArrayData(this.state.data,true,true)}
                          columns={columns}
                          rowClassName="editable-row"
                          pagination={false}
                          size="small"
                        />
                        </div>
                        {/* <Pagination
                            showSizeChanger
                            // onShowSizeChange={this.onShowSizeChange}
                            showQuickJumper
                            defaultCurrent={1}
                            total={500}
                            // onChange={this.Pagination}
                            className={style.Pagination}
                            size="small"
                        /> */}
                        </Card>
                     
                        
            </div>
        )
    }
}

export default connect()(DataMapping)